package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.entity.SpecGroup;
import com.leyou.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService specParamService;
    @Override
    public List<SpecGroupDTO> querySpecGroup(Integer id) {
        System.out.println("查询规格参数组和参数执行了");
        //先查询规格参数组
        List<SpecGroup> category_id = this.query().eq("category_id", id).list();
        //转换为dto
        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(category_id);
        //不存在抛出异常
        if (CollectionUtils.isEmpty(specGroupDTOS)){
            throw new LyException(404,"该分类id下没有规格参数组~~");
        }
        //再查询规格参数表
        List<SpecParam> param = specParamService.query().eq("category_id", id).list();
        //根据规格组id分组
        //以流的形式
        Map<Long, List<SpecParam>> collect = param.stream().collect(Collectors.groupingBy(SpecParam::getGroupId));
        //再将specRaram封装到specdto中
        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            List<SpecParam> specParams = collect.get(specGroupDTO.getId());
            List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(specParams);
            specGroupDTO.setParams(specParamDTOS);
        }
        return specGroupDTOS;
    }
}